#include "TilesetApp.hpp"
#include "video/Texture.hpp"
#include "video/Tilemap.hpp"
#include "video/Tileset.hpp"
#include "framework/Entity.hpp"
#include "framework/DrawHandler.hpp"
#include "framework/Scene2d.hpp"
#include "framework/Event.hpp"
#include "framework/DrawEvent.hpp"
#include "video/Screen.hpp"

namespace yep
{

TilesetApp TilesetApp::_instance;

class TilemapEntity: public Entity, public DrawHandler
{
public:
	TilemapEntity(Tilemap &tilemap) :
			_tilemap(tilemap)
	{
	}

	double getDepth()
	{
		return 0;
	}

	Vector2 getTopLeft()
	{
		return {5,5};
	}

	Vector2 getBottomRight()
	{
		return {16*4+5,16*4+5};
	}

	void evCreate(Event &event)
	{
		event.getScene().handleDraw(*this);
	}

	void evDraw(DrawEvent &event)
	{
		Screen &screen = event.getScreen();
//		_tilemap.draw(screen, Vector2(5,5));
		_tilemap.draw(screen, Vector2(5,5), Vector2(16,16), screen.getSize());
	}
private:
	Tilemap &_tilemap;
};

Scene & TilesetApp::getFirstScene()
{
	if (!_scene)
	{

		_scene = new Scene2d();
		_tilesetTexture = new Texture("res/tilesets/try1.png");
		_tileset = new Tileset(*_tilesetTexture, 32, 32);
		Tilemap *tilemap;
		tilemap = new Tilemap{
//			1, 1, 1, 1,
//			1, 1, 1, 1,
//			1, 1, 1, 1,
//			1, 1, 1, 1
//			1, 2, 3, 4,
//			5, 6, 7, 8,
//			9, 10, 11, 12,
//			13, 14, 15, 16
			1, 1, 1, 14, 13, 1, 1, 2, 1, 1,
			6, 6, 6, 14, 13, 6, 6, 2, 6, 6,
			6, 6, 6, 14, 13, 6, 6, 2, 6, 6,
			6, 6, 6, 14, 13, 6, 6, 2, 6, 6,
			6, 6, 6, 14, 13, 6, 6, 2, 6, 6,
			6, 6, 6, 14, 13, 6, 6, 2, 6, 6,
			4, 4, 6, 14, 13, 6, 6, 2, 6, 6,
			6, 6, 6, 14, 13, 2, 2, 2, 6, 6,
			6, 6, 6, 14, 13, 6, 5,16, 6, 6,
			6, 6, 6, 14, 13, 6, 6, 6, 6, 6
		};
		tilemap->setMapWidth(10);
		tilemap->setMapHeight(10);
		tilemap->setTileset(*_tileset);
		TilemapEntity *tileMapEntity = new TilemapEntity(*tilemap);
		_scene->add(*tileMapEntity);
	}
	return *_scene;
}

TilesetApp::TilesetApp() :
		Application("tileset/Tilemap Test", "Tests the tilemap. Figures out the best interface for Future TileLayer class")
{
	_scene = NULL;
}

} // namespace yep
